package com.phy.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.log4j.Logger;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.ResolverConfig;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;

import com.phy.mail.servlets.Domains;

public class AchieveSys {
	private static Logger logger = Logger.getLogger(Domains.class.getClass());

	// 返回所有mx记录
	@SuppressWarnings("null")
	public String[] ObtainAllMX(String domain) throws NamingException,
			NameNotFoundException {
		String returnRecorder = "";
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put("java.naming.factory.initial",
				"com.sun.jndi.dns.DnsContextFactory");
		env.put("java.naming.provider.url", "dns://8.8.8.8/");
		DirContext dirContext = new InitialDirContext(env);
		Attributes attrs = dirContext.getAttributes(domain,
				new String[] { "MX" });//
		for (NamingEnumeration<?> ae = attrs.getAll(); ae != null
				&& ae.hasMoreElements();) {
			Attribute attr = (Attribute) ae.next();
			NamingEnumeration<?> e = attr.getAll();
			while (e.hasMoreElements()) {
				String element = e.nextElement().toString();
				//System.out.println("这条mx记录是:" + element);
				returnRecorder += " " + element;
			}
		}
		// 把此条记录以分隔符空格号为标准堆放进数组
		String[] mxArray = null;
		if (returnRecorder.toString().trim() != "") {
			mxArray = StringToArray.convertStrToArray(returnRecorder.trim());
		} else {
			mxArray = StringToArray.convertStrToArray("0");
		}
		return mxArray;
	}

	/**
	 * 返回优先级最高的mx记录
	 */
	public String ObtainSingleMX(String[] allmx) {
		// 把下标值为偶数的数组元素压入栈(动态数组)
		ArrayList<Integer> grades = new ArrayList<Integer>();
		String mx = null;
		if (allmx[0].toString().trim() != "0") {
			for (int i = 0; i < allmx.length; i++) {
				// System.out.println("the string is:" + allmx[i]);
				try {
					if (i % 2 == 0 && allmx[i].toString().trim() != "") {
						// System.out.println("the mx 记录的优先级是:" + allmx[i]);
						grades.add(Integer.parseInt(allmx[i].toString().trim()));
					}
				} catch (NumberFormatException e) {
					logger.error("AchieveSys.82:" + e.getMessage());
				}
			}
			// 找出该栈中这些数组元素值最小的值
			int min = (Integer) grades.get(0);
			for (int n = 0; n < allmx.length; n++) {
				if ((String.valueOf(min).equals(allmx[n]))) {
					mx = allmx[n + 1];
				}
			}
		} else {
			mx = "无法获取mx记录";
		}
		return mx;
	}

	// 取优先级最高的使用，链接telnet获取邮件系统信息
	public String EmailSystemInfo(String MailExchanger) {
		// 定义一个字符串，存放取得的邮件系统信息
		String informations="";
		if (MailExchanger.toString().trim() != "无法获取mx记录" && MailExchanger.toString().charAt(0)!='.') {
			logger.info("AchieveSys.111:与服务器端25端口需要通信的字符串是:" + MailExchanger);
			informations = SocketValue(MailExchanger, 25, 8000);
			logger.info("AchieveSys.113:连25端口返回的返回值是:" + informations);
		} 
		else {
			informations = "Sorry，无法获取mx记录的域名是查找不到相关邮箱系统信息的。";
		}
		return informations;
	}

	public String SocketValue(String MailExchanger, int port, int timeout) {
		String s=MailExchanger;
		char[] newString=s.toCharArray();
		String ss="";
		if(s.endsWith(".")){
			for(int i=0;i<newString.length-1;i++){
				ss+=newString[i];
			}
			logger.info("AchieveSys.128:新的字符串hostname是"+ss);
		}
		String value = "";
		Socket socket = new Socket(); // 实例化socket
		SocketAddress socketAddress = new InetSocketAddress(ss, port); // 获取sockaddress对象
		BufferedReader in = null;
		try {
			socket.connect(socketAddress, 2000); // 连接socket并设置连接超时为2秒，如果2秒后服务端还没有响应，则弹出异常信息。
			socket.setSoTimeout(timeout);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			boolean more = true;
			while (more) {
				value = in.readLine();
				if (value == null) {
					value = "";
					more = false;
				} else {
					more = true;
				}
				in.close();
			}
			socket.close();
		} catch (SocketTimeoutException ou) {
			if (!socket.isClosed() && socket.isConnected()) {
				System.out.println("读取数据超时");
				value = "读取数据超时";
				logger.error("AchieveSys.144:" + value);
			} else {
				logger.info("AchieveSys.146:连接超时");
				value = "连接超时";
				logger.error("AchieveSys.148:" + value);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
			System.out.println("未知主机异常");// DNS解析不了
			logger.error("AchieveSys.152:" + e.getMessage());
		} catch (SocketException e) {
			e.printStackTrace();
			logger.error("AchieveSys.155:" + e.getMessage());
		}
		catch (IOException e) {
			 //e.printStackTrace();
			//logger.error("AchieveSys.158:"+e.getStackTrace());
		}
		return value;
	}
	public boolean checkARecord(String host){
		String ARecord="";
		boolean flag=true;
		new ArrayList<String>();
		Lookup lookUpAgent = null;
		try {
			lookUpAgent = new Lookup(host, Type.A);
		} catch (TextParseException e) {
			e.printStackTrace();
		}
		// Send DNS query
		lookUpAgent.run();
		Record [] records = lookUpAgent.getAnswers();
		if(records!=null){
			for(int i=0 ; i<records.length ; i++) {
			ARecord=(String)ARecord+records[i].toString().trim();
			}
		}else{
			flag=false;
		}
		if(ARecord.indexOf("127.0.0.1")!=-1){
			//ARecord="该域名的A记录指向有错";
			flag=false;
		}
		return flag;
	}
/*
	public boolean isReachable(String ip) {
		boolean flag = false;
		Runtime r = Runtime.getRuntime();
		int timeout = 2;
		String pingCommand = "ping " + ip + " -w " + timeout;
		BufferedReader in = null;
		try {
			Process p = r.exec(pingCommand);
			if (p == null) {
				System.out.println("Failed.");
			}
			in = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			while ((line = in.readLine()) != null) {
				System.out.println(line);
				if (line.contains("bytes from")) {
					System.out.println("Conected.");
					p.destroy();
					flag = true;// 可达
				}
			}
		} catch (Exception ex) {
			System.out.println("Failed.");
		} finally {
			try {
				in.close();
			} catch (Exception ex) {
			}
		}
		return flag;
	}
	*/
}
